import express, { Express, Request, Response } from 'express';
import logger from 'morgan';
import { createServer } from 'vite';
import fs from 'fs-extra';
import path from 'path';
const NODE_ENV = process.env.NODE_ENV;
const app: Express = express();
//打印请求日志的中间件
(async function () {

  if (NODE_ENV === 'development') {
    const vite = await createServer({
      //如果配置为html的话，这不是一个原原本本的vite开发服务器
      server: {
        middlewareMode: 'ssr'
      }
    });
    //中间件能处理的就直接返回了
    app.use(vite.middlewares);
    app.use(logger('dev'));
    app.use('*', async (req, res) => {
      //获取当前根目录下面的绝对路径 
      const template = await fs.readFile(path.join(__dirname, 'index.html'), 'utf8');
      const hmrTemplate = await vite.transformIndexHtml(req.url, template)
      const { render } = await vite.ssrLoadModule('/src/server-entry.tsx');
      const appHtml = await render(req.url);
      const html = hmrTemplate.replace('<!--ssr-outlet-->', appHtml);
      res.set('Content-Type', 'text/html;charset=utf8');
      res.send(html);
    })
  } else {
    app.use('*.html', async (req, res) => {
      serve(req, res);
    })
    app.use(express.static(path.resolve(__dirname, 'client')));
    app.use('*', async (req, res) => {
      serve(req, res);
    })
  }
  async function serve(req, res) {
    const template = await fs.readFile(path.join(__dirname, 'client/index.html'), 'utf8');
    const { render } = require('./server/server-entry.js');
    const appHtml = await render(req.url);
    const html = template.replace('<!--ssr-outlet-->', appHtml);
    res.set('Content-Type', 'text/html;charset=utf8');
    res.send(html);
  }
  app.listen(8888, () => console.log('ssr server started on 8888'));
})();